package com.oscar.ehome.provider.zxing.client.android.decode;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.view.View;

import com.google.zxing.ResultPoint;
import com.oscar.ehome.R;
import com.oscar.ehome.provider.zxing.client.android.camera.CameraInterface;
import com.oscar.ehome.provider.zxing.client.android.camera.CameraManager;
import com.oscar.ehome.provider.zxing.client.android.util.Util;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.ToastUtil;

import java.util.ArrayList;
import java.util.Collection;

/**
 * This view is overlaid on top of the camera preview. It adds the viewfinder rectangle and partial transparency outside it, as well as the laser scanner animation and result points.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 */
public final class ViewfinderView extends View {

    private static final int[] SCANNER_ALPHA =
            {0, 64, 128, 192, 255, 192, 128, 64};
    private static final int OPAQUE = 0xFF;
    private static final long ANIMATION_DELAY = 10L;
    private static final int CURRENT_POINT_OPACITY = 0xFF;
    private static final int MAX_RESULT_POINTS = 20;
    private static final int POINT_SIZE = 6;

    private CameraManager cameraManager;
    private final Paint paint;
    private Bitmap resultBitmap;
    private final int maskColor;
    private final int resultColor;
    private final int laserColor;
    private final int resultPointColor;
    private final int frameColor;
    private int scannerAlpha;
    private Collection<ResultPoint> possibleResultPoints;
    private Collection<ResultPoint> lastPossibleResultPoints;

    private int margin = 0;
    private String scan_type;
    Context mContext;

    private Camera.Face[] mFaces;
    private Matrix mMatrix = new Matrix();
    private RectF mRect = new RectF();
    private Drawable mFaceIndicator = null;

    // This constructor is used when the class is built from an XML resource.
    public ViewfinderView(Context context, AttributeSet attrs) {
        super(context, attrs);

        // Initialize these once for performance rather than calling them every time in onDraw().
        paint = new Paint(Paint.DITHER_FLAG);
        Resources resources = getResources();
        maskColor = resources.getColor(R.color.viewfinder_masks);
        resultColor = resources.getColor(R.color.result_view);
        laserColor = resources.getColor(R.color.viewfinder_laser);
        resultPointColor = resources.getColor(R.color.possible_result_points);
        frameColor = resources.getColor(R.color.viewfinder_frame);
        scannerAlpha = 0;
        possibleResultPoints = new ArrayList<ResultPoint>(5);
        lastPossibleResultPoints = null;

        mContext = context;
        mFaceIndicator = getResources().getDrawable(R.mipmap.moren);

    }

    public void setFaces(Camera.Face[] faces) {
        this.mFaces = faces;
        invalidate();
    }

    public void clearFaces() {
        mFaces = null;
        invalidate();
    }

    public void setCameraManager(CameraManager cameraManager, String scan_type) {
        this.cameraManager = cameraManager;
        this.scan_type = scan_type;
    }

    @Override
    public void onDraw(Canvas canvas) {
        if (cameraManager == null) {
            return; // not ready yet, early draw before done configuring
        }
        Rect frame = cameraManager.getFramingRect(scan_type);
        if (frame == null) {
            return;
        }
        int width = canvas.getWidth();
        int height = canvas.getHeight();

        // Draw the exterior (i.e. outside the framing rect) darkened
//        paint.setColor(resultBitmap != null ? resultColor : maskColor);
        paint.setColor(getResources().getColor(R.color.viewfinder_cusmask));

        canvas.drawRect(0, 0, width, frame.top, paint);
        canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);
        canvas.drawRect(frame.right, frame.top, width, frame.bottom + 1, paint);
        canvas.drawRect(1, frame.bottom + 1, width, height, paint);

        if (resultBitmap != null) {
            // Draw the opaque result bitmap over the scanning rectangle
            paint.setAlpha(CURRENT_POINT_OPACITY);
            canvas.drawBitmap(resultBitmap, null, frame, paint);
        } else {
            //扫描四角边框大小
            int linewidht = 10;
            paint.setColor(frameColor);
            //扫描四角边框长度
            canvas.drawRect(frame.left, frame.top, (linewidht + frame.left), (50 + frame.top), paint);
            canvas.drawRect(frame.left, frame.top, (50 + frame.left), (linewidht + frame.top), paint);
            canvas.drawRect(((0 - linewidht) + frame.right), frame.top, (1 + frame.right), (50 + frame.top), paint);
            canvas.drawRect((-50 + frame.right), frame.top, frame.right, (linewidht + frame.top), paint);
            canvas.drawRect(frame.left, (-49 + frame.bottom), (linewidht + frame.left), (1 + frame.bottom), paint);
            canvas.drawRect(frame.left, ((0 - linewidht) + frame.bottom), (50 + frame.left), (1 + frame.bottom), paint);
            canvas.drawRect(((0 - linewidht) + frame.right), -1 + (-49 + frame.bottom), (1 + frame.right), (1 + frame.bottom), paint);
            canvas.drawRect((-50 + frame.right), ((0 - linewidht) + frame.bottom), frame.right, (linewidht - (linewidht - 1) + frame.bottom), paint);

            paint.setAntiAlias(true);
            //扫描框中间线宽度
            paint.setStrokeWidth(4);
//            canvas.drawLine(frame.left, frame.top + margin, frame.right, frame.top + margin, paint);

//            canvas.drawLine(frame.right-margin, frame.top, frame.right-margin, frame.bottom, paint);

            //绘制头像显示矩形框
            int marginR = 32;
            Rect lineRectAvatar = new Rect();
            float avatarw = (frame.right - frame.left) * 0.7f;
            float avatarh = (frame.bottom - frame.top) * 0.3f;
            int outx = (frame.left + frame.right) / 2;
//            int outy = (frame.top + frame.bottom)/2;
            lineRectAvatar.left = outx - (int) (avatarw * 2 / 5);
            lineRectAvatar.right = outx + (int) (avatarw * 1 / 3);
            lineRectAvatar.top = (int) (frame.bottom - avatarh) - marginR;
            lineRectAvatar.bottom = frame.bottom - marginR;

            //绘制上去
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.idcard_first_head_5);
            canvas.drawBitmap(bmp, null, lineRectAvatar, paint);
//            canvas.drawBitmap(bmp,0,0,null);
            bmp.recycle();
            bmp = null;

            paint.setColor(Color.WHITE);
            canvas.drawLine(outx - (int) (avatarw / 2), (int) (frame.bottom - avatarh) - marginR, outx + (int) (avatarw / 2), (int) (frame.bottom - avatarh) - marginR, paint);
            canvas.drawLine(outx - (int) (avatarw / 2), frame.bottom - marginR, outx + (int) (avatarw / 2), frame.bottom - marginR, paint);
            canvas.drawLine(outx - (int) (avatarw / 2), (int) (frame.bottom - avatarh) - marginR, outx - (int) (avatarw / 2), frame.bottom - marginR, paint);
            canvas.drawLine(outx + (int) (avatarw / 2), (int) (frame.bottom - avatarh) - marginR, outx + (int) (avatarw / 2), frame.bottom - marginR, paint);

            //动态定义出扫描线矩形  复制修改
            Rect lineRect = new Rect();
            lineRect.left = frame.right - margin - 18;
            lineRect.right = frame.right - margin;
            lineRect.top = frame.top + 18;
            lineRect.bottom = frame.bottom - 18;

            //绘制上去
            canvas.drawBitmap(((BitmapDrawable) (getResources()
                            .getDrawable(R.mipmap.scan_line))).getBitmap(), null, lineRect,
                    paint);
            //扫描框扫描速度快慢
//            margin = (margin + 12) % (frame.bottom - frame.top);
            margin = (margin + 15) % (frame.right - frame.left);
            paint.setAlpha(SCANNER_ALPHA[scannerAlpha]);
            //扫描框+位置的显示
            scannerAlpha = (scannerAlpha + 1) % SCANNER_ALPHA.length;
            int vmiddle = frame.height() / 2 + frame.top;
            int hmiddle = frame.width() / 2 + frame.left;
            canvas.drawRect(hmiddle - 20, vmiddle - 1, hmiddle + 20, vmiddle + 2, paint);
            canvas.drawRect(hmiddle - 1, vmiddle - 20, hmiddle + 2, vmiddle + 20, paint);
            postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top, frame.right, frame.bottom);
        }

        ///人脸
        if (mFaces != null && mFaces.length > 0) {
            boolean isMirror = false;
            int Id = CameraInterface.getInstance().getCameraId();
            if (Id == Camera.CameraInfo.CAMERA_FACING_BACK) {
                isMirror = false;
            } else if (Id == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                isMirror = true;
            }

            Util.prepareMatrix(mMatrix, isMirror, 90, getWidth(), getHeight());

            //  new Paint(Paint.ANTI_ALIAS_FLAG).setColor(Color.rgb(98, 212, 68));
            canvas.save();// 保存Canvas状态（状态1）
            mMatrix.postRotate(0);
            canvas.rotate(-0);
//            for (int i = 0; i < mFaces.length; i++) {
//                mRect.set(mFaces[i].rect);
//                mMatrix.mapRect(mRect);
//                mFaceIndicator.setBounds(Math.round(mRect.left), Math.round(mRect.top),
//                        Math.round(mRect.right), Math.round(mRect.bottom));
////                mFaceIndicator.draw(canvas);
//            }
            if (CommonUtils.isFirst) {
                CommonUtils.isFirst = false;
                CommonUtils.idcard = 1;
            }
            canvas.restore(); // 返回最新的save状态，即状态2
            ToastUtil.e("mwh", "人脸识别");
        }
    }

    public void drawViewfinder() {
        Bitmap resultBitmap = this.resultBitmap;
        this.resultBitmap = null;
        if (resultBitmap != null) {
            resultBitmap.recycle();
        }
        invalidate();
    }

    /**
     * Draw a bitmap with the result points highlighted instead of the live scanning display.
     *
     * @param barcode An image of the decoded barcode.
     */
    public void drawResultBitmap(Bitmap barcode) {
        resultBitmap = barcode;
        invalidate();
    }

    public void addPossibleResultPoint(ResultPoint point) {
        possibleResultPoints.add(point);
    }

}
